package top.wecreate.view;

import java.util.LinkedList;
import java.util.List;

import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.example.dynamicmain.R;

public class DanmakuView extends LinearLayout {

	private static final String TAG = DanmakuView.class.getSimpleName();

	private int DEFAULT_TAG_PADDING = getResources().getDimensionPixelOffset(
			R.dimen.default_tag_padding);
	private int DEFAULT_TAG_PADDING_TOP = getResources()
			.getDimensionPixelOffset(R.dimen.default_tag_padding_top);
	private int DEFAULT_LAYOUT_MARGIN_TOP = getResources()
			.getDimensionPixelOffset(R.dimen.default_tag_layout_margin_top);

	private int MAX_WIDTH = getResources().getDimensionPixelOffset(
			R.dimen.max_width);
	private int MAX_HEIGHT = getResources().getDimensionPixelOffset(
			R.dimen.max_height);
	private int TEXT_SIZE = 10;

	public enum ScreenStyle {
		UNKNOW, PORT, LAND
	}

	private ScreenStyle mScreenStyle = ScreenStyle.UNKNOW;
	private Context mContext;
	private boolean isLockScreen = false;
	private boolean inAnim = false;
	private HandlerTimer mTimer;
	private List<RoomSendMessageInfo> mComments;
	private int tickMills = 300;
	private int animDuration = tickMills / 3; // 淡出，移动，淡入。所以除以3.

	private int mTotalHeight;
	private Boolean isDoingReShow = false;
	private Boolean isPause = false;
	private boolean isLive = true;
	private int mCount = 1;

	public DanmakuView(Context context) {
		this(context, null);
		mContext = context;
	}

	public DanmakuView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
		mContext = context;
	}

	public DanmakuView(Context context, AttributeSet attrs, int defStyleAttr) {
		super(context, attrs, defStyleAttr);
		mContext = context;
		setOrientation(VERTICAL);
		setGravity(Gravity.BOTTOM | Gravity.LEFT);
		init();
	}

	/**
	 * 获取是否是竖屏
	 * 
	 * @return
	 */
	public ScreenStyle getScreenStyle() {
		return mScreenStyle;
	}

	/**
	 * 锁定屏幕。无法继续显示消息。
	 * 
	 * @param comment
	 */
	public synchronized void lockScreen(RoomSendMessageInfo comment) {
		if (isLockScreen) {
			return;
		}

		isLockScreen = true;
		mComments.clear();
		mComments.add(comment);
	}

	/**
	 * 解锁屏幕。可以继续显示消息。
	 * 
	 * @param info
	 */
	public void unlockScreen(RoomSendMessageInfo info) {
		if (isLockScreen) {
			isLockScreen = false;
			setData(info);
		}
	}

	/**
	 * 开始循环显示内容。
	 */
	public void start() {
		mTimer.start();
	}

	/**
	 * 关闭循环显示。
	 */
	public void stop() {
		mTimer.cancel();
	}

	/**
	 * TODO ???
	 */
	public void screenStop() {
		stop();
	}

	/**
	 * TODO ???
	 * 
	 * @param count
	 */
	public void setDanmakuBackPlay(int count) {
		isLive = true;
		this.mCount = count;
	}

	/**
	 * TODO 清屏重新显示？
	 * 
	 * @param info
	 */
	public void reShow(RoomSendMessageInfo info) {

		stop();
		clearChildAnimation();
		removeAllViews();
		mComments.clear();

		start();
		setData(info);
	}

	/**
	 * 设置要显示的数据。
	 * 
	 * @param comment
	 */
	public synchronized void setData(RoomSendMessageInfo comment) {
		if (null == comment) {
			return;
		}

		if (isLockScreen) {
			return;
		}

		if (mComments.size() > 20) {
			mComments.remove(mComments.size() - 1);
		}
		Log.d(TAG, "======setData==mComments.add ==" + comment.getContent());
		mComments.add(comment);
		hasNewAdded = true;
		autoRemoveOldTimer.cancel();
	}

	private void startAutoRemoveTimer() {
		autoRemoveOldTimer.cancel();
		autoRemoveOldTimer.start();
	}

	private boolean hasNewAdded = false;
	private HandlerTimer autoRemoveOldTimer;

	/**
	 * 设置屏幕方向。
	 * 
	 * @param vertical
	 */
	public void setScreenStyle(ScreenStyle screenStyle) {
		if (screenStyle == mScreenStyle) {
			return;
		}

		mScreenStyle = screenStyle;

		stop();
		initResource();
		clearChildAnimation();
		resizeSelf(mScreenStyle);
		resizeAllViews();
		start();
	}

	private void resizeAllViews() {
		boolean needRemove = false;
		int currentHeight = 0;
		int childCount = getChildCount();
		for (int i = childCount - 1; i >= 0; i--) {
			View oldChildView = getChildAt(i);
			if (needRemove) {
				removeView(oldChildView);
				continue;
			}

			RoomSendMessageInfo msgInfo = (RoomSendMessageInfo) oldChildView
					.getTag();
			LinearLayout danmuItemView = generateDanmuItemView(msgInfo);
			int widthMeasureSpec = MeasureSpec.makeMeasureSpec(MAX_WIDTH,
					MeasureSpec.UNSPECIFIED);
			int heightMeasureSpec = MeasureSpec.makeMeasureSpec(
					MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
			danmuItemView.measure(widthMeasureSpec, heightMeasureSpec);

			int danmuItemHeight = danmuItemView.getMeasuredHeight();

			if (currentHeight + danmuItemHeight > MAX_HEIGHT) {
				// 直接remove掉
				needRemove = true;
				removeView(oldChildView);
			} else {
				needRemove = false;
				currentHeight += danmuItemHeight;
				removeView(oldChildView);
				addView(danmuItemView, i);
			}
		}
	}

	private void resizeSelf(ScreenStyle screenStyle) {
		DanmakuView view = this;
		int height;

		if (screenStyle == ScreenStyle.PORT) {
			MAX_WIDTH = Utils.getScreenWidth() / 2;
			int top = Utils.dip2px(mContext, 30);
			height = 8 * Utils.getScreenWidth() / 15 - top;
			FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
					MAX_WIDTH, height);
			params.setMargins(16, top / 2, 0, top / 2);
			view.setLayoutParams(params);
			MAX_HEIGHT = height;
		} else if (screenStyle == ScreenStyle.LAND) {
			int top = Utils.dip2px(mContext, 80);
			MAX_WIDTH = getResources().getDimensionPixelOffset(
					R.dimen.max_width);
			height = Utils.getScreenWidth() - top;
			FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
					MAX_WIDTH, height);
			params.setMargins(16, top / 2, 0, top / 2);
			view.setLayoutParams(params);
			MAX_HEIGHT = height;
		}
	}

	private void init() {
		mComments = new LinkedList<RoomSendMessageInfo>();
		mTimer = new HandlerTimer(tickMills, 1) {

			@Override
			public void onTick() {
				onTimerTick();
			}

			@Override
			public void onFinish() {
				onTimerFinish();
			}
		};

		autoRemoveOldTimer = new HandlerTimer(5 * 1000, 1) {

			@Override
			public void onTick() {
				hasNewAdded = false;
				removeTopItemView(getChildCount(), null);
				autoRemoveOldTimer.cancel();
			}

			@Override
			public void onFinish() {
				autoRemoveOldTimer.cancel();
			}
		};

		initResource();
	}

	private void changeTickTimer(int tickMills) {
		clearChildAnimation();
		animDuration = tickMills / 3; // 淡出，移动，淡入。所以除以3.
		mTimer.setTickMills(tickMills);
	}

	private void initResource() {
		if (mScreenStyle == ScreenStyle.PORT
				|| mScreenStyle == ScreenStyle.UNKNOW) {
			DEFAULT_TAG_PADDING = getResources().getDimensionPixelOffset(
					R.dimen.default_tag_padding);
			DEFAULT_TAG_PADDING_TOP = getResources().getDimensionPixelOffset(
					R.dimen.default_tag_padding_top);
			DEFAULT_LAYOUT_MARGIN_TOP = getResources().getDimensionPixelOffset(
					R.dimen.default_tag_layout_margin_top);

			MAX_HEIGHT = Utils.dip2px(mContext, 200) - 120;
			MAX_WIDTH = Utils.getScreenWidth() / 2;

			TEXT_SIZE = 14;
		} else if (mScreenStyle == ScreenStyle.LAND) {
			DEFAULT_TAG_PADDING = getResources().getDimensionPixelOffset(
					R.dimen.landscape_tag_padding);
			DEFAULT_TAG_PADDING_TOP = getResources().getDimensionPixelOffset(
					R.dimen.landscape_tag_padding_top);
			DEFAULT_LAYOUT_MARGIN_TOP = getResources().getDimensionPixelOffset(
					R.dimen.landscape_tag_layout_margin_top);

			MAX_WIDTH = getResources().getDimensionPixelOffset(
					R.dimen.max_width);
			MAX_HEIGHT = Utils.getScreenWidth() - 300;

			TEXT_SIZE = 16;
		}
	}

	private synchronized void onTimerTick() {
		Log.d(TAG, "======HandlerTimer==inAnim ==" + inAnim);
		if (inAnim) {
			return;
		}
		if (mComments.size() > 10) {
			changeTickTimer(150);
			Log.d(TAG, "======HandlerTimer==changeTickTimer(150) =="
					+ mComments.size());
		} else {
			changeTickTimer(300);
			Log.d(TAG, "======HandlerTimer==changeTickTimer(300) =="
					+ mComments.size());
		}

		if (mComments.size() == 0) {
			return;
		}

		// 每次都获取List的第一个
		RoomSendMessageInfo needAddDanmuInfo = mComments.get(0);

		Log.d(TAG,
				"======HandlerTimer==needAddDanmuInfo =="
						+ needAddDanmuInfo.getContent());
		LinearLayout danmuItemView = generateDanmuItemView(needAddDanmuInfo);
		if (danmuItemView == null) {
			return;
		}

		

		int widthMeasureSpec = MeasureSpec.makeMeasureSpec(MAX_WIDTH,
				MeasureSpec.UNSPECIFIED);
		int heightMeasureSpec = MeasureSpec.makeMeasureSpec(
				MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
		danmuItemView.measure(widthMeasureSpec, heightMeasureSpec);

		int danmuItemHeight = danmuItemView.getMeasuredHeight();
		int needRemoveSize = getNeedRemoveViewSize(danmuItemHeight);
		removeTopItemView(needRemoveSize, danmuItemView);
	}

	private void removeTopItemView(final int needRemoveSize,
			final LinearLayout danmuItemView) {
		inAnim = true;
		
		if (danmuItemView != null) {
			// 不在autoRemove中
			if (needRemoveSize == 0) {
				// 说明全部移除结束了。
				translateChildren(danmuItemView);
				return;
			}
		} else {
			// 在autoRemove中
			// 如果此时有新添加的item，应该立即结束。
			if (hasNewAdded) {
				autoRemoveOldTimer.cancel();
				clearChildAnimation();
				inAnim = false;
				return;
			}

			if (needRemoveSize == 0) {
				// 说明全部移除结束了。
				inAnim = false;
				return;
			}
		}

		final View needRemoveView = getChildAt(0);
		AlphaAnimation animAlpha = new AlphaAnimation(1.0f, 0.0f);// 淡出
		animAlpha.setAnimationListener(new EndAnimationListener() {

			@Override
			public void onAnimationEnd(Animation animation) {
				// remove掉
				removeView(needRemoveView);
				// 接着移动下一个
				removeTopItemView(needRemoveSize - 1, danmuItemView);
			}

		});
		animAlpha.setDuration(animDuration / needRemoveSize);
		needRemoveView.setAnimation(animAlpha);
		needRemoveView.startAnimation(animAlpha);

	}

	private void translateChildren(final LinearLayout danmuItemView) {
		int childCount = getChildCount();

		if (childCount == 0) {
			addDanmuItemView(danmuItemView);
			return;
		}

		for (int i = 0; i < childCount; i++) {
			final View view = getChildAt(i);
			TranslateAnimation animTranslate = new TranslateAnimation(0, 0, 0,
					0 - danmuItemView.getMeasuredHeight());
			if (i == childCount - 1) {
				animTranslate.setAnimationListener(new EndAnimationListener() {

					@Override
					public void onAnimationEnd(Animation animation) {
						view.clearAnimation();
						addDanmuItemView(danmuItemView);
					}

				});
			} else {
				animTranslate.setAnimationListener(new EndAnimationListener() {

					@Override
					public void onAnimationEnd(Animation animation) {
						view.clearAnimation();
					}

				});
			}
			animTranslate.setDuration(animDuration);
			view.setAnimation(animTranslate);
			view.startAnimation(animTranslate);
		}
	}

	private void addDanmuItemView(final View danmuItemView) {
		if (danmuItemView == null) {
			inAnim = false;
			return;
		}

		addView(danmuItemView);

		AlphaAnimation animAlpha = new AlphaAnimation(0.1f, 1.0f);
		animAlpha.setAnimationListener(new EndAnimationListener() {

			@Override
			public void onAnimationEnd(Animation arg0) {
				Object tag = danmuItemView.getTag();
				mComments.remove(tag);
				// 结束了
				inAnim = false;
				startAutoRemoveTimer();
			}
		});
		animAlpha.setDuration(animDuration);
		danmuItemView.setAnimation(animAlpha);
		danmuItemView.startAnimation(animAlpha);
	}

	private int getNeedRemoveViewSize(int danmuItemHeight) {
		int currentHeight = danmuItemHeight;

		int childCount = getChildCount();
		for (int i = childCount - 1; i >= 0; i--) {
			int childHeight = getChildAt(i).getHeight();
			if (currentHeight + childHeight > MAX_HEIGHT) {
				return i + 1; // 个数，从1开始的嘛。。
			} else {
				currentHeight += childHeight;
			}
		}

		return 0;
	}

	private LinearLayout generateDanmuItemView(RoomSendMessageInfo danmuInfo) {
		String content = danmuInfo.getContent();
		if (null == content || TextUtils.isEmpty(content.trim())) {
			return null;
		}
		content = content.trim();

		final Button button = new Button(mContext);
		button.setMaxWidth(MAX_WIDTH);
		button.setGravity(Gravity.LEFT);
		button.setTextSize(TEXT_SIZE);
		button.setText(content);
		FontStyle danmuStyle = danmuInfo.getStyle();
		if (null != danmuStyle && !TextUtils.isEmpty(danmuStyle.getFontColor())) {
			button.setTextColor(Color.parseColor(danmuStyle.getFontColor()));
		} else {
			button.setTextColor(getResources().getColor(android.R.color.white));
		}
		button.setShadowLayer(2, 2, 2,
				getResources().getColor(R.color.shadow_color));
		button.setPadding(DEFAULT_TAG_PADDING, DEFAULT_TAG_PADDING_TOP,
				DEFAULT_TAG_PADDING, DEFAULT_TAG_PADDING_TOP);
		button.setBackgroundResource(R.drawable.live_danmaku_bg);
		LayoutParams btnLayoutParams = new LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		btnLayoutParams.topMargin = DEFAULT_LAYOUT_MARGIN_TOP;

		LinearLayout danmuItemView = new LinearLayout(mContext);
		danmuItemView.addView(button, btnLayoutParams);

		danmuItemView.setTag(danmuInfo);

		return danmuItemView;
	}

	private void onTimerFinish() {
		// TODO Auto-generated method stub

	}

	private synchronized void clearChildAnimation() {
		for (int i = 0; i < getChildCount(); i++) {
			View danmuItemView = getChildAt(i);
			danmuItemView.clearAnimation();
		}
		inAnim = false;
	}

	private abstract class EndAnimationListener implements
			Animation.AnimationListener {

		@Override
		public void onAnimationRepeat(Animation arg0) {

		}

		@Override
		public void onAnimationStart(Animation arg0) {

		}
	}

}
